import { useEffect, useState } from "react"
import Navigate from "../components/Navigate.jsx"
import "./Management.css"
import { fetchAdminInfoService, 
    listUsersService, 
    userDetailService, 
    updateUserExpService, 
    updateUserBTService, 
    updateUserGroupService, 
    banUserService, 
    unbanUserService } from "../api/AdminApi"

// 防抖hook
const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

function Management() {
  const [admin, setAdmin] = useState(null)
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [total, setTotal] = useState(0)
  const [totalPage, setTotalPage] = useState(0)
  const [pageNumbers, setPageNumbers] = useState([])
  const [searchParams, setSearchParams] = useState({
    current: 1,
    size: 10,
    username: "",
    email: "",
    permissionGroup: "",
    status: "",
  })
  const [viewingItem, setViewingItem] = useState(null)
  const [showModal, setShowModal] = useState(false)
  const [searchLoading, setSearchLoading] = useState(false)
  const [isEditing, setIsEditing] = useState(false)
  const [editForm, setEditForm] = useState({
    experience: 0,
    bt: 0,
    permissionGroup: 0,
    status: 0,
  })
  const [saveLoading, setSaveLoading] = useState(false)
  const [message, setMessage] = useState({ type: "", text: "" })
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)

  // 对搜索参数进行防抖处理
  const debouncedSearchParams = useDebounce(searchParams, 500)

  useEffect(() => {
    loadAdmin()
  }, [])

  useEffect(() => {
    loadUsers()
  }, [debouncedSearchParams])

  const loadAdmin = async () => {
    try {
      const response = await fetchAdminInfoService()
      if (response.status === 200) {
        setAdmin(response.data)
      } else {
        setError("获取管理员信息失败")
      }
    } catch (err) {
      setError("获取管理员信息失败")
    }
  }

  const loadUsers = async () => {
    setLoading(true)
    setSearchLoading(true)
    try {
      const response = await listUsersService(debouncedSearchParams)
      if (response.status === 200) {
        setUsers(response.data.records)
        setTotal(response.data.total)
        setTotalPage(Math.ceil(response.data.total / response.data.size))
        setPageNumbers(
          getPageNumbers(debouncedSearchParams.current, Math.ceil(response.data.total / response.data.size)),
        )
      } else {
        setError("加载用户失败")
      }
    } catch (err) {
      setError("加载用户失败")
    } finally {
      setLoading(false)
      setSearchLoading(false)
    }
  }

  const handleSearchChange = (e) => {
    const { name, value } = e.target
    setSearchParams((prev) => ({
      ...prev,
      [name]: value,
      current: 1, // 重置到第一页
    }))
  }

  const handleReset = () => {
    setSearchParams({
      current: 1,
      size: 10,
      username: "",
      email: "",
      permissionGroup: "",
      status: "",
    })
  }

  const handleJumpToPage = (e) => {
    if (e.key === "Enter") {
      const page = Number.parseInt(e.target.value)
      if (page >= 1 && page <= totalPage) {
        setSearchParams({
          ...searchParams,
          current: page,
        })
      }
    }
  }

  const handleView = async (item) => {
    try {
      const response = await userDetailService(item.id)
      if (response.status === 200) {
        setViewingItem(response.data)
        setEditForm({
          experience: response.data.userExp.experience,
          bt: response.data.userExp.bt,
          permissionGroup: response.data.userInfo.permissionGroup,
          status: response.data.userInfo.status,
        })
        setShowModal(true)
        setIsEditing(false)
        setMessage({ type: "", text: "" })
      } else {
        setError("获取用户详情失败")
      }
    } catch (err) {
      setError("获取用户详情失败")
    }
  }

  const closeModal = () => {
    setShowModal(false)
    setViewingItem(null)
    setIsEditing(false)
    setMessage({ type: "", text: "" })
  }

  const handleEditToggle = () => {
    if (isEditing) {
      // 取消编辑，恢复原始值
      setEditForm({
        experience: viewingItem.userExp.experience,
        bt: viewingItem.userExp.bt,
        permissionGroup: viewingItem.userInfo.permissionGroup,
        status: viewingItem.userInfo.status,
      })
    }
    setIsEditing(!isEditing)
    setMessage({ type: "", text: "" })
  }

  const handleEditFormChange = (e) => {
    const { name, value } = e.target
    setEditForm((prev) => ({
      ...prev,
      [name]: name === "experience" || name === "bt" ? Number(value) : Number(value),
    }))
  }

  const handleSave = async () => {
    setSaveLoading(true)
    setMessage({ type: "", text: "" })

    try {

      // 检查经验值和BT是否有变化
      if (editForm.experience !== viewingItem.userExp.experience) {
        const response = await updateUserExpService(viewingItem.userInfo.id, {
          experienceDelta: editForm.experience,
        })
        if (response.status !== 200) {
          throw new Error("更新经验值失败")
        }
      }

      if (editForm.bt !== viewingItem.userExp.bt) {
        const response = await updateUserBTService(viewingItem.userInfo.id, {
          btDelta: editForm.bt,
        });
        if (response.status !== 200) {
          throw new Error("更新BT失败");
        } 
      }

      // 检查权限组是否有变化
      if (editForm.permissionGroup !== viewingItem.userInfo.permissionGroup) {
        const response = await updateUserGroupService(viewingItem.userInfo.id, {
          permissionGroup: editForm.permissionGroup,
        })
        if (response.status !== 200) {
          throw new Error("更新权限组失败")
        }
      }

      // 检查状态是否有变化
      if (editForm.status !== viewingItem.userInfo.status) {
        if (editForm.status === 1) {
          const response = await banUserService(viewingItem.userInfo.id)
          if (response.status !== 200) {
            throw new Error("封禁用户失败")
          }
        } else {
          const response = await unbanUserService(viewingItem.userInfo.id)
          if (response.status !== 200) {
            throw new Error("解封用户失败")
          }
        }
      }

      // 更新本地数据
      setViewingItem((prev) => ({
        ...prev,
        userExp: {
          ...prev.userExp,
          experience: editForm.experience,
          bt: editForm.bt,
        },
        userInfo: {
          ...prev.userInfo,
          permissionGroup: editForm.permissionGroup,
          status: editForm.status,
        },
      }))

      // 更新用户列表中的数据
      setUsers((prev) =>
        prev.map((user) =>
          user.id === viewingItem.userInfo.id
            ? {
                ...user,
                permissionGroup: editForm.permissionGroup,
                status: editForm.status,
              }
            : user,
        ),
      )

      setIsEditing(false)
      setMessage({ type: "success", text: "用户信息修改成功！" })

      // 3秒后清除消息
      setTimeout(() => {
        setMessage({ type: "", text: "" })
      }, 3000)
    } catch (err) {
      console.error("保存失败:", err)
      setMessage({ type: "error", text: "保存失败，请重试！" })
    } finally {
      setSaveLoading(false)
    }
  }

  const handleNavigateClick = (item) => {
    console.log("导航到:", item.name, item.path)
    // 这里可以添加路由跳转逻辑
    // 例如: router.push(item.path)
    setMobileMenuOpen(false)
  }

  const toggleMobileMenu = () => {
    setMobileMenuOpen(!mobileMenuOpen)
  }

  const getPermissionGroupName = (group) => {
    const groups = {
      0: "见习生",
      1: "毕业生",
      2: "初级铁驭",
      3: "合格铁驭",
      4: "知名铁驭",
      5: "荣耀铁驭",
      6: "传奇铁驭",
      7: "BT至尊",
    }
    return groups[group] || "未知"
  }

  const formatBytes = (bytes) => {
    if (bytes === 0) return "0 B"
    const k = 1024
    const sizes = ["B", "KB", "MB", "GB", "TB"]
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
  }

  if (loading) return <div className="loading">正在加载...</div>
  if (error) return <div className="error">{error}</div>

  return (
    <div className="admin-layout">
      {/* 导航栏 */}
      <Navigate activeItem="用户管理" onItemClick={handleNavigateClick} />

      {/* 移动端菜单按钮 */}
      <button className="mobile-menu-btn" onClick={toggleMobileMenu}>
        ☰
      </button>

      {/* 主内容区域 */}
      <div className="main-content">
        <div className="management-container">
          {/* 头部 */}
          <div className="header">
            <h2>用户管理</h2>
            <div className="admin-info">管理员：{admin?.username}</div>
          </div>

          {/* 搜索表单 */}
          <div className="search-form">
            <div className="form-group">
              <label>用户名</label>
              <div style={{ position: "relative" }}>
                <input
                  type="text"
                  name="username"
                  value={searchParams.username}
                  onChange={handleSearchChange}
                  placeholder="请输入用户名"
                  className="form-input"
                />
                {searchLoading && searchParams.username && (
                  <div
                    style={{
                      position: "absolute",
                      right: "10px",
                      top: "50%",
                      transform: "translateY(-50%)",
                      fontSize: "12px",
                      color: "#667eea",
                    }}
                  >
                    搜索中...
                  </div>
                )}
              </div>
            </div>
            <div className="form-group">
              <label>邮箱</label>
              <div style={{ position: "relative" }}>
                <input
                  type="text"
                  name="email"
                  value={searchParams.email}
                  onChange={handleSearchChange}
                  placeholder="请输入邮箱"
                  className="form-input"
                />
                {searchLoading && searchParams.email && (
                  <div
                    style={{
                      position: "absolute",
                      right: "10px",
                      top: "50%",
                      transform: "translateY(-50%)",
                      fontSize: "12px",
                      color: "#667eea",
                    }}
                  >
                    搜索中...
                  </div>
                )}
              </div>
            </div>
            <div className="form-group">
              <label>等级</label>
              <select
                name="permissionGroup"
                value={searchParams.permissionGroup}
                onChange={handleSearchChange}
                className="form-select"
              >
                <option value="">全部</option>
                <option value="0">0 见习生</option>
                <option value="1">1 毕业生</option>
                <option value="2">2 初级铁驭</option>
                <option value="3">3 合格铁驭</option>
                <option value="4">4 知名铁驭</option>
                <option value="5">5 荣耀铁驭</option>
                <option value="6">6 传奇铁驭</option>
                <option value="7">7 BT至尊</option>
              </select>
            </div>
            <div className="form-group">
              <label>状态</label>
              <select name="status" value={searchParams.status} onChange={handleSearchChange} className="form-select">
                <option value="">全部</option>
                <option value="0">正常</option>
                <option value="1">封禁</option>
              </select>
            </div>
            <div className="form-group">
              <button onClick={handleReset} className="btn btn-secondary">
                重置
              </button>
            </div>
          </div>

          {/* 表格 */}
          <div className="table-container">
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>用户名</th>
                  <th>邮箱</th>
                  <th>等级</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {users.map((item) => (
                  <tr key={item.id}>
                    <td>{item.id}</td>
                    <td>{item.username}</td>
                    <td>{item.email}</td>
                    <td>
                      {item.permissionGroup} {getPermissionGroupName(item.permissionGroup)}
                    </td>
                    <td>
                      <span className={`status-badge ${item.status === 0 ? "status-normal" : "status-banned"}`}>
                        {item.status === 0 ? "正常" : "封禁"}
                      </span>
                    </td>
                    <td>
                      <button onClick={() => handleView(item)} className="btn btn-link">
                        查看详情
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 分页 */}
          <div className="pagination-container">
            <div className="pagination-info">共 {total} 条数据</div>
            <div className="pagination-controls">
              <button
                onClick={() => {
                  if (searchParams.current > 1) {
                    setSearchParams((prev) => ({ ...prev, current: prev.current - 1 }))
                  }
                }}
                disabled={searchParams.current === 1}
                className="pagination-btn"
              >
                ‹
              </button>
              {pageNumbers.map((number, index) => (
                <button
                  key={index}
                  onClick={() => {
                    if (typeof number === "number") {
                      setSearchParams((prev) => ({ ...prev, current: number }))
                    }
                  }}
                  disabled={number === "..."}
                  className={`pagination-btn ${searchParams.current === number ? "active" : ""}`}
                >
                  {number}
                </button>
              ))}
              <button
                onClick={() => {
                  if (searchParams.current < totalPage) {
                    setSearchParams((prev) => ({ ...prev, current: prev.current + 1 }))
                  }
                }}
                disabled={searchParams.current === totalPage}
                className="pagination-btn"
              >
                ›
              </button>
              <div className="pagination-jump">
                <select
                  value={searchParams.size}
                  onChange={(e) => {
                    setSearchParams((prev) => ({ ...prev, current: 1, size: e.target.value }))
                    setTotalPage(Math.ceil(total / e.target.value))
                  }}
                >
                  <option value={10}>10 条/页</option>
                  <option value={20}>20 条/页</option>
                  <option value={50}>50 条/页</option>
                  <option value={100}>100 条/页</option>
                </select>
                <span>跳至</span>
                <input type="number" min={1} max={totalPage} onKeyDown={handleJumpToPage} placeholder="页��" />
                <span>页</span>
              </div>
            </div>
          </div>

          {/* 查看/编辑模态框 */}
          {showModal && (
            <div className="modal-overlay" onClick={closeModal}>
              <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                  <h2>{isEditing ? "编辑用户信息" : "用户详细信息"}</h2>
                  {message.text && (
                    <div className={`message ${message.type === "success" ? "message-success" : "message-error"}`}>
                      {message.text}
                    </div>
                  )}
                </div>
                {viewingItem && (
                  <div className="modal-body">
                    {/* 基本信息 - 只读 */}
                    <div className="detail-section">
                      <h3 className="section-title">基本信息</h3>
                      <div className="detail-item">
                        <label className="detail-label">用户ID</label>
                        <div className="detail-value">{viewingItem.userInfo.id}</div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">用户名</label>
                        <div className="detail-value">{viewingItem.userInfo.username}</div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">邮箱地址</label>
                        <div className="detail-value">{viewingItem.userInfo.email}</div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">邀请人</label>
                        <div className="detail-value">{viewingItem.userInfo.invitedBy || "无"}</div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">注册时间</label>
                        <div className="detail-value">
                          {new Date(viewingItem.userInfo.createdTime).toLocaleString()}
                        </div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">最后更新</label>
                        <div className="detail-value">
                          {new Date(viewingItem.userInfo.updatedTime).toLocaleString()}
                        </div>
                      </div>
                    </div>

                    {/* 可编辑信息 */}
                    <div className="detail-section">
                      <h3 className="section-title">权限与状态</h3>
                      <div className="detail-item">
                        <label className="detail-label">用户等级</label>
                        {isEditing ? (
                          <select
                            name="permissionGroup"
                            value={editForm.permissionGroup}
                            onChange={handleEditFormChange}
                            className="edit-input"
                          >
                            <option value={0}>0 见习生</option>
                            <option value={1}>1 毕业生</option>
                            <option value={2}>2 初级铁驭</option>
                            <option value={3}>3 合格铁驭</option>
                            <option value={4}>4 知名铁驭</option>
                            <option value={5}>5 荣耀铁驭</option>
                            <option value={6}>6 传奇铁驭</option>
                            <option value={7}>7 BT至尊</option>
                          </select>
                        ) : (
                          <div className="detail-value">
                            {viewingItem.userInfo.permissionGroup} -{" "}
                            {viewingItem.userInfo.permissionGroupName ||
                              getPermissionGroupName(viewingItem.userInfo.permissionGroup)}
                          </div>
                        )}
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">账户状态</label>
                        {isEditing ? (
                          <select
                            name="status"
                            value={editForm.status}
                            onChange={handleEditFormChange}
                            className="edit-input"
                          >
                            <option value={0}>正常</option>
                            <option value={1}>封禁</option>
                          </select>
                        ) : (
                          <div className="detail-value">
                            <span
                              className={`status-badge ${viewingItem.userInfo.status === 0 ? "status-normal" : "status-banned"}`}
                            >
                              {viewingItem.userInfo.status === 0 ? "正常" : "封禁"}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 数据统计 */}
                    <div className="detail-section">
                      <h3 className="section-title">数据统计</h3>
                      <div className="detail-item">
                        <label className="detail-label">上传量</label>
                        <div className="detail-value">{formatBytes(viewingItem.userExp.uploaded)}</div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">下载量</label>
                        <div className="detail-value">{formatBytes(viewingItem.userExp.downloaded)}</div>
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">经验值</label>
                        {isEditing ? (
                          <input
                            type="number"
                            name="experience"
                            value={editForm.experience}
                            onChange={handleEditFormChange}
                            className="edit-input"
                            min="0"
                          />
                        ) : (
                          <div className="detail-value">{viewingItem.userExp.experience.toLocaleString()}</div>
                        )}
                      </div>
                      <div className="detail-item">
                        <label className="detail-label">BT积分</label>
                        {isEditing ? (
                          <input
                            type="number"
                            name="bt"
                            value={editForm.bt}
                            onChange={handleEditFormChange}
                            className="edit-input"
                            min="0"
                          />
                        ) : (
                          <div className="detail-value">{viewingItem.userExp.bt.toLocaleString()}</div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
                <div className="modal-footer">
                  {isEditing ? (
                    <>
                      <button onClick={handleSave} disabled={saveLoading} className="btn btn-primary">
                        {saveLoading ? "保存中..." : "保存修改"}
                      </button>
                      <button onClick={handleEditToggle} disabled={saveLoading} className="btn btn-secondary">
                        取消
                      </button>
                    </>
                  ) : (
                    <>
                      <button onClick={handleEditToggle} className="btn btn-primary">
                        编辑信息
                      </button>
                      <button onClick={closeModal} className="btn btn-secondary">
                        关闭
                      </button>
                    </>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

const getPageNumbers = (current, totalPages, delta = 2) => {
  const pages = []
  const start = Math.max(1, current - delta)
  const end = Math.min(totalPages, current + delta)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  if (start > 1) {
    if (start > 2) pages.unshift("...")
    pages.unshift(1)
  }

  if (end < totalPages) {
    if (end < totalPages - 1) pages.push("...")
    pages.push(totalPages)
  }

  return pages
}

export default Management;